#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import json
import cgi
import datetime
import db_conf
con = None
try:
    qform = cgi.FieldStorage()
    spectrum_id = qform.getvalue('spectrum_id')
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config))
    cur = con.cursor()
    print "Content-type: text/html;charset=utf-8\r\n"
    pa = {}
    pa['aaData'] = []
    select_intensity = 'select distinct(mz), intensity from spectral_peak where spectrum_id = %s order by mz asc' %(spectrum_id)
    cur.execute(select_intensity)
    intensity_rows = cur.fetchall()
    mz = []
    intensity = []
    pos = 0 
    maxpos = 0
    pi = []
    for i_row in intensity_rows:
        pos = pos + 1
        for ii in range(len(i_row)):
            if (ii == 0):
                mz.append(i_row[ii])
            if (ii == 1):
                intensity.append(i_row[ii])
            intensities = ",".join(str(i_val).split(".")[0] for i_val in intensity)
            mz_values = ",".join(str(i_val).split(".")[0] for i_val in mz)
    pi.append(spectrum_id + ":" + intensities + ":" + mz_values + "");
    pa['aaData'].append(pi)
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)    
finally:
    if con:
        con.close()
